<template>
    <div class="modal fade" id="addFollowModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content" style="margin-top: 50px;">
                <div class="modal-header">
                    <h4 class="modal-title" id="myModalLabel"> 写跟进</h4>
                </div>
                <div class="modal-body">
                    <div class="form-horizontal">
                        <div class="form-group">
                            <label class="col-md-4 col-sm-2 control-label">报备人：</label>
                            <div class="col-md-8 col-sm-10">
                                <div class="form-control">
                                    {{this.followUpModal.followPerson}}
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-md-4 col-sm-2 control-label">跟进事宜：</label>
                            <div class="col-md-8 col-sm-10">
                                <select class="form-control" v-model="followType">
                                    <option value="">请选择跟进事宜</option>
                                    <option value="4">内部跟进（仅本部机构可见）</option>
                                    <option value="1" v-res="{code:'menu_0005_0001_0004_0001'}">普通跟进（本部/分销机构均可见）</option>
                                    <!-- <option value="2" v-res="{code:'menu_0005_0001_0004_0002'}">电话跟进</option> -->
                                    <option value="3" v-res="{code:'menu_0005_0001_0004_0003'}" v-if="followUpModal.customerStatus == 6 &&followUpModal.confirmStatus==0">到访</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group" v-if="followType==3" v-res="{code:'menu_0005_0001_0004_0004'}">
                            <label class="col-sm-4 control-label">实际到访时间：</label>
                            <div class="col-sm-4">
                                <DatePicker type="datetime" :disabled="editVisitTime" placeholder="实际到访时间" v-model="params.createTime" style="width: 200px"></DatePicker>
                            </div>
                            <div class="col-sm-4">
                                <button class="btn pull-right o-color saveAndNext" @click="editVisitTime = false">修改实际到访时间</button>
                            </div>
                        </div>
                        <div class="form-group" v-if="followType==3 && checkMobileShow" v-res="{code:'menu_0005_0001_0006_0003'}">
                            <label class="col-sm-4 control-label">短信到访验真：</label>
                            <div class="col-sm-4">
                                <checkMobileComp v-on:checkMobileListener='checkMobileReturn'></checkMobileComp>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="" class="col-sm-4 control-label">跟进描述：</label>
                            <div class="col-sm-8">
                                <textarea rows="3" class="form-control" v-model="params.remark" placeholder="请填写跟进描述"></textarea>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="" class="col-sm-4 control-label">上传图片：</label>
                            <div class="col-sm-8">
                                <ul class="clearfix remindUpload">
                                    <li class="col-sm-4 file-image" v-for="(image,index) in imgesList" :key="index">
                                        <img :src="image.url" width="100%" height="80px" v-if="image.fileType.toLowerCase()=='png'
                                         || image.fileType.toLowerCase()=='jpg' 
                                         || image.fileType.toLowerCase()=='jpeg' 
                                         || image.fileType.toLowerCase()=='gif'" />
                                        <div width="100%" height="80px" class="pic-bg-fj" v-else></div>
                                    </li>
                                    <li class="col-sm-4 file-image">
                                        <div class="file-upload">
                                            <input ref="imageUpload" type="file" class="file-btn" style="width:100%;" name="files" id="files" @change="onFileChange">
                                            <i class="layui-icon"></i>
                                        </div>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn checkedBtn" v-show="btnShow" @click="saveFollow">确定</button>
                    <button type="button" class="btn btn-default" v-show="btnShow" @click="canel">取消</button>
                </div>
            </div>
        </div>
    </div>
</template>
<style scoped>
.remindUpload li {
  margin-top: 8px;
}
.remindUpload .file-upload {
  width: 100%;
  height: 80px;
  padding: 10px;
}
.file-upload .layui-icon {
  font-size: 50px;
  color: #f87142;
}
</style>
<script>
import { formatDate } from "../../assets/js/date.js";
import checkMobileComp from "./components/checkMobileComp.vue";
export default {
  //接收父组件的绑定值
  props: ["followUpModal"],
  data() {
    return {
      //机构信息对象
      params: {
        customerPremisesId: "",
        remark: "",
      },
      btnShow: true,
      imgesList: [],
      followType: "",
      editVisitTime: true,
      checkMobileProps: {
        id: "",
        type: "follow",
      },
      mobileChecked: false,
      checkMobileShow: false,
    };
  },
  components: {
    checkMobileComp,
  },
  watch: {
    //监听父组件绑定值是否改变
    followUpModal: {
      handler: function(val, oldVal) {
        this.checkMobileProps.id = this.followUpModal.customerPremisesId;
        if (this.followUpModal.checkSwitch == "1") {
          this.checkMobileShow = true;
        } else {
          this.checkMobileShow = false;
        }
      },
      //深层监听，当位对象时，若设为true，属性变更时即可触发，若为false，属性无法监听到
      deep: true,
    },
  },
  filters: {
    formatDate(time) {
      let date = new Date(time);
      return formatDate(date, "yyyy-MM-dd hh:mm");
    },
  },
  methods: {
    saveFollow: function() {
      const _self = this;

      if (
        _self.checkMobileShow &&
        !_self.mobileChecked &&
        _self.followType == 3
      ) {
        layer.msg("请先进行短信验真!", { icon: 7, time: 2000 });
        return false;
      }

      if (!_self.params.remark) {
        layer.msg("请填写跟进内容！", { icon: 7, time: 2000 });
        return;
      }
      if (
        (_self.editVisitTime && _self.followType == 3) ||
        _self.followType != 3
      ) {
        this.params.createTime = new Date();
      }
      const url = this.utilHelper.apiUrl + "/api/addFollow";
      const body = {};
      _self.params.customerPremisesId = this.followUpModal.customerPremisesId;
      body.params = _self.params;
      body.params.affixList = this.imgesList;
      body.params.syncFlag = "1";
      body.params.followType = this.followType;
      _self.$http.post(url, body).then(
        (response) => {
          const res = response.body.resData;
          if (res.result == "1") {
            layer.msg("跟进成功");
            this.canel();
            _self.$emit("savefollowUpListener");
            _self.mobileChecked = false;
          } else {
            layer.msg("跟进失败");
          }
        },
        (response) => {
          layer.msg("跟进失败");
        }
      );
    },
    canel: function() {
      $("#addFollowModal").modal("hide");
      this.imgesList = [];
    },
    onFileChange: function(e) {
      layer.load(0, { shade: false }); //弹出加载层
      var files = e.target.files || e.dataTransfer.files;
      if (!files.length) return;
      var size = files[0].size;
      if (size > 3145728) {
        layer.msg("图片大小不能超过3M");
        layer.closeAll("loading"); //关闭加载层
        return;
      }
      this.createImage(files[0]);
    },
    createImage(file) {
      var _self = this;
      var reader = new FileReader();
      reader.readAsDataURL(file);
      let indexNum = file.name.lastIndexOf(".") + 1;
      reader.onload = (e) => {
        //上传附件
        let msg = e.target.result;
        layer.load(0, {
          shade: false,
        }); //弹出加载层
        var myForm = new FormData(); //创建formdata
        var blobBin = _self.dataURLtoBlob(msg); //base64转换blob
        myForm.append("blobObject", blobBin); //想formData添加blob数据
        myForm.append("suffix", file.name.substr(file.name.lastIndexOf("."))); //添加文件后缀
        var url = _self.utilHelper.apiUrl + "/api/uploadBase64ToQiNiu";
        _self.$http.post(url, myForm).then(
          (response) => {
            layer.closeAll("loading"); //关闭加载层
            var data = response.body;
            if (data.result == "1") {
              _self.imgesList.push({
                url: data.resData.imgName,
                fileType: file.name.substr(indexNum),
                isQiNiu: true,
              });
            } else {
              layer.msg("图片上传失败，请重试");
            }
          },
          (response) => {
            layer.msg(response);
          }
        );
      };
    },
    //将base64转换blob
    dataURLtoBlob(dataUrl) {
      var arr = dataUrl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], {
        type: mime,
      });
    },
    init() {
      this.params.createTime = new Date();
      this.followType = "";
      this.params.remark = "";
      this.editVisitTime = true;
    },
    checkMobileReturn(msg) {
      this.mobileChecked = true;
    },
  },
};
</script>